package org.jshand.jxc.business.game;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToolBar;

public class SnakeGamePanel extends JPanel implements ActionListener, KeyListener{


//	@Override
//	public void paint(Graphics g) {
//		g.drawImage()
//		super.paint(g);
//	}

	private JPanel centerPanel;
	
	int x = 0;
	int y = 0;
	int fx = 3;
	
	static int maxCandyx = 25;
	static int maxCandyy = 14;
	
	Random random = new Random();
	
	List<Point> snake = new ArrayList();
	Point candy = createCandyPoint();
	
	boolean isStart = false;
	boolean fail = false;

	private Graphics g2d;

	private JButton startOrPause;

	private JButton addSnakeBtn;

	private JButton subSnakeBtn;

	private JButton candyBtn;
	
	long stepLong = 350;//开始速度
	long nowSpeed = 0 ; //现在速度

	private JButton upSpeedBtn;

	private JButton lowSpeedBtn;
	
	
	public SnakeGamePanel() {
		super();
		
		initToolBar();
		initSnake();
		
		centerPanel = new JPanel();
		
		this.add(centerPanel,BorderLayout.CENTER);
		
		centerPanel.setFocusable(true);
		centerPanel.requestFocus();
		centerPanel.addKeyListener(this);
		centerPanel.setBackground(Color.PINK);
		this.setFocusable(true);
		this.requestFocus();
		this.addKeyListener(this);
			
	}

	public SnakeGamePanel(LayoutManager layout, boolean isDoubleBuffered) {
		super(layout, isDoubleBuffered);
	}

	public SnakeGamePanel(LayoutManager layout) {
		super(layout);
		// TODO Auto-generated constructor stub
	}

	
	
	private void initSnake() {
		for (int i = 0; i < 5; i++) {
			Point p = new Point(-i*30, 0);
			snake.add(p);
		}
		
	}

	private void initToolBar() {

		this.setLayout(new BorderLayout());
		
		JToolBar toolBar = new JToolBar();

		startOrPause = new JButton("♬开始/暂停");
		toolBar.add(startOrPause);
		
		addSnakeBtn = new JButton("升级");
		toolBar.add(addSnakeBtn);
		
		subSnakeBtn = new JButton("降级");
		toolBar.add(subSnakeBtn);
		
		
		upSpeedBtn = new JButton("加速");
		toolBar.add(upSpeedBtn);
		
		lowSpeedBtn = new JButton("减速");
		toolBar.add(lowSpeedBtn);
		
		candyBtn = new JButton("重画糖果");
		toolBar.add(candyBtn);
		
		toolBar.setVisible(true);
		
		this.add(toolBar, BorderLayout.NORTH);
		
		startOrPause.addActionListener(this);
		addSnakeBtn.addActionListener(this);
		subSnakeBtn.addActionListener(this);
		candyBtn.addActionListener(this);
	}

	
	public void paintDirt(){

		g2d = centerPanel.getGraphics();
		if(g2d == null){
			return;
		}
		centerPanel.update(g2d);
		
		
		int step = 30;
		switch (fx) {
			case 1:
				x -= step;
				break;
			case 2:
				y -= step;
				break;
			case 3:
				x += step;
				break;
			case 4:
				y += step;
				break;
		}

		printSnake();
		
	}
	
	
	private void printSnake() {
		//画糖果
		g2d.setColor(Color.YELLOW);
		g2d.fillRect(candy.x, candy.y,30,30);
		
		//设置坐标
		g2d.setColor(Color.BLACK);
		for (int i = snake.size()-1; i >=0; i--) {
			if(i==0){
				snake.get(i).x = x;
				snake.get(i).y = y;
				g2d.fillRect(x, y, 30, 30);
			}else{
				Point point = snake.get(i-1);
				snake.get(i).x = point.x;
				snake.get(i).y = point.y;
				g2d.drawRect(point.x, point.y, 30, 30);
			}
		}
		
		
		for (int i = snake.size()-1; i >=0; i--) {
			Point point = snake.get(i);
			g2d.setColor(Color.BLACK);
			g2d.drawRect(point.x, point.y, 30, 30);
		}
		
		ifNewCandy();
		
		
	}

	

	/**
	 * 生成糖果位置，并绘画到panel中
	 * private final static int width = 800;
	 * private final static int height = 500;
	 * 800
	 */
	
	
	private void ifNewCandy(){
		ifNewCandy(false);
	}
	private void ifNewCandy(boolean nessary) {
		//如果蛇头跟糖果重合，需要重新设置糖果地址
		if(nessary || snake.get(0).getX() == candy.getX() && snake.get(0).getY() == candy.getY() ){
			
			
			candy.setLocation(createCandyPoint());
			//重合升级 蛇的长度
			addSnakeLevel();
			nowSpeed += 10;
		}
		
	}
	
	
	private Point createCandyPoint(){
		int x = 0;
		int y = 0;
		while(true){
			x = random.nextInt(maxCandyx)*30;
			y = random.nextInt(maxCandyy)*30;
			
			boolean contains = false;
			for (int i = 0; i < snake.size(); i++) {
				Point point = snake.get(i);
				if(point.x == x && point.y == y){
					contains = true;
					break;
				}
			}
		
			if(!contains){
				break;
			}
		}
		return new Point(x, y);
	}
	

	@Override
	public void keyPressed(KeyEvent e) {
//		System.out
//				.println(e.getKeyCode()+"----"+KeyEvent.getKeyText(e.getKeyCode()));
		//System.out.println("fx--"+fx);
		int oldfx = fx;
		
		switch (e.getKeyCode()) {
			case 37:
				fx = 1;
				break;
			case 38:
				fx = 2;
				break;
			case 39:
				fx = 3;
				break;
			case 40:
				fx = 4;
				break;
			case 32:
				runOrStart();
				break;
			default:
				break;
		}
		
		if(Math.abs(fx-oldfx)==2){
			fail = true;
		}
		
	}
	private void runOrStart() {
		isStart = !isStart;
		if(!isStart){
			return;
		}
		
		Runnable run = new Runnable() {
			
			@Override
			public void run() {
				int count = 4;
				while(true){
					
					if(!isStart){
						break;
					}
					try {
						count--;
						long sl = stepLong - nowSpeed;
						if(sl<2){
							sl = 2;
						}
						System.out.println("现在的速度---"+sl);
						Thread.sleep(sl);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if(isFail()){
//						g2d.drawString("GameOver", 220, 200);
						JOptionPane.showMessageDialog(null, "游戏终止你的蛇撞墙死了(*^__^*),当前得分--"+(snake.size()*100), "失败", JOptionPane.WARNING_MESSAGE, null);
						return;
					}
			    	paintDirt();
				}
			}

			
		};
		new Thread(run).start();
		
	}


	
	private boolean isFail() {
		//如果是其他 已经失败的情况，直接返回失败，其他的情况需要判断
		if(fail){
			return fail;
		}
		
		
		//1 判断 舌头是否超出 左边界 和上边界
		if(x<0 || y<0){
			fail = true;
		}
		return fail;
	}

	@Override
	public void keyTyped(KeyEvent e) {}
	
	@Override
	public void keyReleased(KeyEvent e) {}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == startOrPause){
			runOrStart();
		}
		
		//给蛇升级/降级
		else if(e.getSource() == addSnakeBtn){//给蛇升级
			addSnakeLevel();
		}else if(e.getSource() == subSnakeBtn){
			snake.remove(snake.size()-1);
		}
		
		
		//重新画糖果
		else if(e.getSource() == upSpeedBtn){
			nowSpeed += 5;
		}else if(e.getSource() == lowSpeedBtn){
			nowSpeed -= 5;
		}
		
		//重新画糖果
		else if(e.getSource() == candyBtn){
			//画糖果 
			g2d = centerPanel.getGraphics();
			centerPanel.update(g2d);
			ifNewCandy(true);
		}
		
		centerPanel.requestFocus();
	}

	
	private void addSnakeLevel(){
		snake.add(new Point(-100,-100));
	}
	
	
}
